<script setup lang="ts">
import type { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import type { RuleObject } from 'ant-design-vue/lib/form';

import type { SysDeptResp } from '#/type/sys_dept';
import type { SysMenuResp } from '#/type/sys_menu';
import type { SysRoleResp } from '#/type/sys_role';
import type { SysUserResp } from '#/type/sys_user';

import { computed, ref, watch } from 'vue';
import type { PropType } from 'vue';

import {
  Col,
  Divider,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  RadioGroup,
  Row,
  Switch,
  TreeSelect,
} from 'ant-design-vue';

import { antTreeHandler } from '#/utils/antTools';

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object as PropType<SysRoleResp> | undefined,
    default: () => {},
  },
  menuList: {
    type: Array as PropType<Array<SysMenuResp>>,
    default: () => [],
  },
  deptList: {
    type: Array as PropType<Array<SysDeptResp>>,
    default: () => [],
  },
  userList: {
    type: Array as PropType<Array<SysUserResp>>,
    default: () => [],
  },
});

const emit = defineEmits(['ok', 'cancel']);
const formRef = ref();
const formRules: { [k: string]: RuleObject | RuleObject[] } = {
  role_name: [
    {
      type: 'string',
      required: true,
      message: '请输入名称',
      trigger: 'blur',
    },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  role_code: [
    {
      type: 'string',
      required: true,
      message: '请输入编码',
      trigger: 'blur',
    },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
};
// 创建本地数据副本
const localData = ref<SysRoleResp>({ ...props.data });
// 在 props.data 变化时更新本地数据
watch(
  () => props.data,
  (newData) => {
    localData.value = { ...newData } as SysRoleResp;
  },
  { deep: true },
);
const dataScopeOptions = [
  {
    label: '全部',
    value: 1,
  },
  {
    label: '自定义',
    value: 2,
  },
  {
    label: '本部门及子部门',
    value: 3,
  },
  {
    label: '本部门',
    value: 4,
  },
  {
    label: '本人',
    value: 5,
  },
];
const menuTreeData = computed(() => {
  const list = props.menuList;
  if (!list || !Array.isArray(list) || list.length === 0) return [];
  return antTreeHandler(list, 'menu_id', 'menu_name', 'parent_id');
});
const deptTreeData = computed(() => {
  const list = props.deptList;
  if (!list || !Array.isArray(list) || list.length === 0) return [];
  return antTreeHandler(list, 'dept_id', 'dept_name', 'parent_id');
});

// const userTreeData = computed(() => {
//   let list = props.userList
//   if (!list || !Array.isArray(list) || list.length === 0) return []
//   const seen = new Set();
//   let deptList = list.map(item => {
//     return {
//       user_id: 'dept_' + item.dept_id,
//       nick_name: item.dept_name,
//       pid: 'dept_' + item.dept_pid,
//       disabled: true
//     }
//   }).filter(item => {
//     if (seen.has(item.user_id)) {
//       return false;
//     }
//     seen.add(item.user_id);
//     return true;
//   });
//
//   list = list.map(item => {
//     return {user_id: item.dept_id+"_"+item.user_id, nick_name: item.nick_name, pid: 'dept_' + item.dept_id,}
//   })
//
//   list = [...list, ...deptList]
//   return antTreeHandler(list, 'user_id', 'nick_name', 'pid');
// })

const modalSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      emit('ok', localData.value);
    })
    .catch((_: ValidateErrorEntity) => {
      message.error({
        content: '请检查表单填写是否正确',
        duration: 1,
      });
    });
};
</script>

<template>
  <Modal
    :mask-closable="false"
    :open="open"
    :style="{ maxWidth: '50%', width: '50%' }"
    :title="localData ? '编辑' : '新建'"
    @cancel="emit('cancel')"
    @ok="modalSubmit"
  >
    <Divider />
    <Form
      ref="formRef"
      :label-col="{ span: 6 }"
      :model="localData"
      :rules="formRules"
      :wrapper-col="{ span: 18 }"
      layout="horizontal"
    >
      <Divider orientation="left">基本信息</Divider>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="名称" name="role_name">
            <Input
              v-model:value="localData.role_name"
              placeholder="请输入名称"
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="编码" name="role_code">
            <Input
              v-model:value="localData.role_code"
              placeholder="请输入编码"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="状态" name="status">
            <Switch
              v-model:checked="localData.status"
              :checked-value="1"
              :un-checked-value="0"
              checked-children="启用"
              un-checked-children="禁用"
            />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="排序" name="sort">
            <InputNumber
              v-model:value="localData.sort"
              placeholder="请输入排序"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="24">
          <FormItem
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            label="备注"
            name="remark"
          >
            <Input.TextArea
              v-model:value="localData.remark"
              :rows="2"
              placeholder="请输入备注"
            />
          </FormItem>
        </Col>
      </Row>
      <Divider orientation="left">操作权限</Divider>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="操作权限" name="data_scope">
            <TreeSelect
              v-model:value="localData.menu_ids"
              :tree-data="menuTreeData"
              multiple
              placeholder="请选择操作权限"
            />
          </FormItem>
        </Col>
      </Row>
      <Divider orientation="left">数据权限</Divider>
      <Row :gutter="16">
        <Col :span="24">
          <FormItem
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 21 }"
            label="数据权限"
            name="data_scope"
          >
            <RadioGroup
              v-model:value="localData.data_scope"
              :options="dataScopeOptions"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col v-if="localData.data_scope === 2" :span="12">
          <FormItem label="部门" name="custom_dept_ids">
            <TreeSelect
              v-model:value="localData.custom_dept_ids"
              :tree-data="deptTreeData"
              multiple
              placeholder="请选择部门"
            />
          </FormItem>
        </Col>
        <!--        <Col :span="12" v-if="true">-->
        <!--          <FormItem label="用户" name="custom_user_ids">-->
        <!--            <TreeSelect v-model:value="localData.custom_user_ids" :treeData="userTreeData" multiple placeholder="请选择用户"/>-->
        <!--          </FormItem>-->
        <!--        </Col>-->
      </Row>
    </Form>
    <Divider />
  </Modal>
</template>

<style scoped></style>
